﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace Zinnia.Common
{
    /// <summary>
    /// 轻量级日志帮助类
    /// </summary>
    public static class LoggerHelper
    {
        private static IDictionary<string, MiniLogger> _miniLoggerDictionary = new ConcurrentDictionary<string, MiniLogger>();
        public static object lock_obj = new object();
        public static MiniLogger GetMiniLogger(string name = "")
        {
            if (string.IsNullOrWhiteSpace(name)) name = "zinnia";
            if (!_miniLoggerDictionary.ContainsKey(name))
            {
                lock (lock_obj)
                {
                    if (!_miniLoggerDictionary.ContainsKey(name))
                    {
                        _miniLoggerDictionary.Add(name, new MiniLogger($@"Logs\[DATE]\{name}.log"));
                    }
                }
            }
            return _miniLoggerDictionary[name];
        }
    }

    /// <summary>
    /// 轻量级日志
    /// </summary>
    public class MiniLogger
    {
        private readonly string _path;

        internal MiniLogger(string path)
        {
            _path = path;
        }
        public void Write(string message)
        {
            var now = DateTime.Now;
            message = string.Format(@"{1}{0}", message, now);
            var path = _path.Replace("[DATE]", string.Format("{0:yyyy-MM-dd}", now));
            path = Regex.Replace(path, @"\|(?<name>\w+)\|", e =>
            {
                var name = e.Groups["name"].Value;
                return AppDomain.CurrentDomain.GetData(name) + "";
            }, RegexOptions.IgnoreCase);
            //path = Regex.Replace(path, "\\+|/+", "\\");
            var dir = DirectoryHelper.GetApplicationRootPath() + Path.GetDirectoryName(path);
            if (dir != null)
            {
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }
            path = DirectoryHelper.GetApplicationRootPath() + path;
            lock (this)
            {
                File.AppendAllText(path, message + "\r\n", Encoding.UTF8);
            }
        }

        public void Write(Exception ex)
        {
            Write("", ex);
        }

        public void Write(string message, Exception ex)
        {
            Write(message + ex);
        }

        public void Write(object json)
        {
            //Write(JsonConvert.SerializeObject(json));
        }
    }
}
